package cn.kiliter.web.servlet;

import cn.kiliter.model.Product;
import cn.kiliter.serviece.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/addcart")
public class addcartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idstr = request.getParameter("id");
        int id=0;
        if(idstr!=null&&!"".equals(idstr)){
            id=Integer.parseInt(idstr);
        }
        ProductService service=new ProductService();
        Product p=service.findProDuctById(id);
        Map<Product,Integer> cart =( Map<Product,Integer>)request.getSession().getAttribute("cart");
        if(cart==null){
            cart = new HashMap<Product, Integer>();
            cart.put(p,1);
        }else{
            if(cart.containsKey(p)){
                cart.put(p, cart.get(p) + 1);
            }else{
                cart.put(p, 1);
            }
        }
        for(Map.Entry<Product, Integer> entry : cart.entrySet()){
            System.out.println(entry.getKey() + "数量" + entry.getValue());
        }
        request.getSession().setAttribute("cart",cart);
        String a1 = "<a href=\"" + request.getContextPath()+"/showProductByPage\">继续购物</a>";
        String a2 = "&nbsp;&nbsp;<a href=\"" + request.getContextPath()+"/cart.jsp\">查看购物车</a>";
        response.getWriter().write(a1);
        response.getWriter().write(a2);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
